package com.tbit.uqbike.protocol.AnalyzeImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.protocol.ABaseHandleObj;
import com.tbit.uqbike.protocol.IMqAnalyze;
import com.tbit.uqbike.tergateway.entity.MqJsonMsg;
import com.tbit.uqbike.tergateway.entity.RemoteControl;
import com.tbit.uqbike.tergateway.entity.TerControlOrder;
import com.tbit.uqbike.tergateway.entity.TerSyncParamNotice;
import com.tbit.uqbike.util.CharsetName;
import com.tbit.uqbike.util.ConstDefine;
import com.tbit.uqbike.util.StringUtil;
import org.springframework.amqp.core.Message;

import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by MyWin on 2017/5/11.
 */
public class MqAnalyzer implements IMqAnalyze {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MqAnalyzer.class);

    @Override
    public List<ABaseHandleObj> analyzeMqMsg(Message message) {
        List<ABaseHandleObj> list = new LinkedList<ABaseHandleObj>();
        try {
            String msgString = new String(message.getBody(), Charset.forName(CharsetName.UTF_8));
            // 先打印出日志
            logger.info(String.format("MQ RecvMsg:%s", msgString));
            // 进行json解析
            MqJsonMsg mqJsonMsg = JSON.parseObject(msgString, MqJsonMsg.class);
            if (null != mqJsonMsg) {
                if (mqJsonMsg.msgId == ConstDefine.MQ_MSG_ID_CONTROL_TER) {
                    TerControlOrder terControlOrder = JSON.parseObject(mqJsonMsg.data, TerControlOrder.class);
                    if (null != terControlOrder) {
                        RemoteControl remoteControl = terControlOrder.getRemoteControl(mqJsonMsg);
                        list.add(remoteControl);
                    }
                } else if (mqJsonMsg.msgId == ConstDefine.MQ_MSG_ID_TER_SYNC_CHANGE) {
                    TerSyncParamNotice terSyncParamNotice = JSON.parseObject(mqJsonMsg.data, TerSyncParamNotice.class);
                    if (null != terSyncParamNotice) {
                        list.add(terSyncParamNotice);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("analyzeMqMsg Error", e);
        }
        return list;
    }

    public static String buildPushMsg(Object data, Integer msgId) {
        return buildPushMsg(data, msgId, StringUtil.Empty);
    }

    public static String buildPushMsg(Object data, Integer msgId, String feedback) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", msgId);
        jsonObject.put("feedback", feedback);
        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }
}
